package com.hong.spring.transaction.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hong.spring.transaction.dao.UserDao;
import com.hong.spring.transaction.entity.User;
import com.hong.spring.transaction.service.IUserService;
import com.hong.spring.transaction.utils.TransactionUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Auther: csh
 * @Date: 2020/8/3 18:14
 * @Description:用户实现
 */
@Service
public class UserServiceImpl implements IUserService {

    private static Logger log = LogManager.getLogger(UserServiceImpl.class);

    @Autowired
    private PlatformTransactionManager txManager;

    @Autowired
    private UserDao userDao;

    @Autowired
    private TransactionUtils transactionUtils;

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void add(User user) {
        log.info("添加用户信息{}", JSONObject.toJSONString(user));
        userDao.save(user);
    }

    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public void add2(User user) {
        log.info("添加用户信息2{}", JSONObject.toJSONString(user));
        userDao.save(user);
        try{
            throw new RuntimeException();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Transactional(propagation = Propagation.MANDATORY)
    @Override
    public void add3(User user) {
        log.info("添加用户信息3{}", JSONObject.toJSONString(user));
        userDao.save(user);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public void add4(User user) {
        log.info("添加用户信息4{}", JSONObject.toJSONString(user));
        userDao.save(user);
    }

    @Transactional(propagation = Propagation.NOT_SUPPORTED)
    @Override
    public void add5(User user) {
        log.info("添加用户信息5{}", JSONObject.toJSONString(user));
        userDao.save(user);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void update(User user) {
        log.info("更新用户信息{}", JSONObject.toJSONString(user));
        user.setAge(111);
        int i=1/0;
    }

    @Override
    public int handlerTransaction(User user) {
        TransactionStatus begin = transactionUtils.begin();
        try {
            int save = userDao.save(user);
            int i = 1/0;
            transactionUtils.commit(begin);
            return save;
        }catch (Exception e){
            transactionUtils.rollabck(begin);
        }
        return 0;

    }
}
